package pers.mor.tomcat.classloader;

import cn.hutool.log.LogFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class WebappClassLoader extends URLClassLoader {

    public WebappClassLoader(String base, CommonClassLoader classLoader) {
        super(new URL[]{}, classLoader);
        try {
            File webInfoFolder = new File(base, "WEB-INF");
            if (!webInfoFolder.exists()) {
                LogFactory.get().info("发现: {} 目录缺失", webInfoFolder.getAbsolutePath());
                return;
            }

            File classesFolder = new File(webInfoFolder, "classes");
            if (!classesFolder.exists()) {
                LogFactory.get().info("发现: {} 目录缺失", classesFolder.getAbsolutePath());
                return;
            }

            URL url = new URL("file:" + classesFolder.getAbsolutePath() + "/");
            this.addURL(url);

            File lib = new File(webInfoFolder, "lib");
            if (!lib.exists()) {
                LogFactory.get().info("发现: {} 目录缺失", lib.getAbsolutePath());
                return;
            }

            File[] jarFiles = lib.listFiles();
            for (File jar : jarFiles) {
                if (jar.getName().endsWith("jar")) {
                    url = new URL("file:" + jar.getAbsolutePath());
                    this.addURL(url);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
